var express = require('express');
var router = express.Router();
//导入lowdb
const lowdb = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync(__dirname + '/../data/db.json');

//导入shortid
const shortid = require('shortid');
const moment = require('moment');
const jzblistModel = require('../models/jzblistModel');
//读取db对象
const db = lowdb(adapter);

//console.log(moment('2023-02-24').toDate())
//当前时间
//console.log(moment(new Date()).format('YYYY-MM-DD'));



//记帐本列表
router.get('/jzblist', function(req, res, next) {
  //读取mongodb数据库集合信息
  jzblistModel.find().sort({time: -1}).exec().then(data => {
    console.log(data);
    res.render('list',{xfjl:data,moment:moment});//render响应ejs内容
  }).catch(err => {
    res.status(500).send('读取失败~~~');
  })
    
    
  
});

//添加记录
router.get('/jzbjl/jilu', function(req, res, next) {
  res.render('jzbjl');
});

//新增记录
router.post('/jzbjl', (req, res) => {
  //获取请求体数据
  //console.log(req.body)
  // let book = new jzblistModel({
  //   ...req.body,
  //   time: moment(req.body.time).toDate()
  // })
  // book.save().then(data => {
  //   console.log(data)
  //   res.render('添加记录',{msg:'添加成功哦-----', url:'/jzblist'});
  //   //关闭数据库连接
  //   //mongoose.disconnect();
  // }).catch(err => {console.log(err)})
  jzblistModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then(data => {
    console.log(data)
    res.render('添加记录',{msg:'添加成功哦-----', url:'/jzblist'});
  }).catch(err => {
    console.log(err)
    res.status(500).send('插入失败');
  })
  // //生成id
  // let id = shortid.generate();
  // //写入文件
  // //db.get('jilu').push({id:id,...req.body}).write();
  // //添加到顶端
  // db.get('jilu').unshift({id:id,...req.body}).write();
  
});

//删除记录
router.get('/jzbshanchu/:id',(req,res) => {
  //获取params的id参数
  let id =req.params.id;
  // db.get('jilu').remove({id:id}).write();
  //删除数据库中的数据
  jzblistModel.deleteOne({_id:id}).then(data => {
    //提醒
    res.render('添加他记录',{msg:'删除成功ok-----', url:'/jzblist'});
  }).catch(err =>{
    res.status(500).send('删除数据数据失败~~');
  })
  
});
module.exports = router;